//封装一个表单校验插件
//   --一个文本框只对应一个校验规则

//将校验逻辑封装在对象里
var strategies = {
    //不为空
    isNonEmpty : function (value,errorMsg){
        if(value === ''){
            return errorMsg
        }
    },
    //限制最小长度
    minLength : function (value, length, errorMsg){
        if( value.length < length){
            return errorMsg
        }
    },
    //限制号码
    isMobile : function (value ,errorMsg){
        if(!/(^1[3|5|8][0-9]{9}$)/.test(value)){
            return errorMsg
        }
    }
}

//实现一个Validator类
var Validator = function () {
    this.cache = [] //保存校验规则
};
Validator.prototype.add = function (dom, rule, errorMsg) {
    var ary = rule.split(':')  //分割参数
    this.cache.push(function(){
        var strategy = ary.shift();
        ary.unshift( dom.value );
        ary.push(errorMsg);
        return strategies[strategy].apply(dom, ary );
    });
};

Validator.prototype.start = function () {
    var msg = []  //用于收集所有错误信息
    for(var i = 0;i<this.cache.length;i++){
        var oneMsg=this.cache[i]()
        if(oneMsg){
            msg.push(oneMsg)
        }
    }
    if(msg.length!==0){
        return msg
    }
}

//封装一个验证方法
var validataFunc = function () {
    var validator = new Validator() //创建一个validator对象
    /**********添加校验规则 ******************/
    validator.add(registerFrom.userName, 'isNonEmpty','用户名不为空')
    validator.add(registerFrom.password, 'minLength:6','密码长度不能小于6位')
    validator.add(registerFrom.phoneNumber,'isMobile', '手机号码格式不正确')

    var errorMsg = validator.start()//获取校验结果
    return errorMsg //返回校验结果
}

var registerFrom = document.getElementById('registerFrom');
registerFrom.onsubmit = function(){
    var errorMsg = validataFunc();//收集所有错误信息
    if(errorMsg){
        console.log(errorMsg);//如果有错误信息 打印
        return false  //阻止表单提交
    }
}

